import json
import random

import requests
from flask import Flask, jsonify
from flask import request

import config
from delete import delete_vector
from exts import db
from filter import query_collection
from photo_interposition import create_media_structure
from save import process_and_insert_data

from split_into_groups import create_clips
# from insert_data import insert_data
from merge_data import merge_data
from flask_migrate import Migrate
from models import *

app = Flask(__name__)
app.config.from_object(config)

db.init_app(app)
migrate = Migrate(app, db)


# 成片接口
@app.route('/', methods=['POST'])
def movie():
    vector_resource = []
    music = []
    res = Subtitles()
    Content = request.get_json().get("Content")
    MediaUrl = request.get_json().get("MediaUrl")
    oss_save_url = request.get_json().get("oss_save_url")
    template_id = request.get_json().get("template_id")
    endpoint = request.get_json().get("endpoint")
    # 背景音乐
    background_music = request.get_json().get("background_music")
    # 按照几句话分
    clip_mode = request.get_json().get("clip_mode")
    # 音效
    audio = request.get_json().get("audio")
    audio_urls = request.get_json().get("audio_urls")
    duration = request.get_json().get("duration")
    # print(audio_urls)

    # return jsonify(audio_urls)

    # parenthesis = request.get_json().get("parenthesis", [])
    # print(audio_urls)
    # return jsonify(audio_urls)
    audio_clips = []
    # 判断 按照什么样的 模式添加素材 全素材 中量素材 大量素材
    if clip_mode != 0:
        # 按照传入的数据 来分割
        clips = create_clips(data=Content, mode=clip_mode)
        # 调用 query_collection 函数，并将结果和 end_time 结合起来

        # 转换数据
        converted_data = []
        for item in clips:
            new_item = {
                'text': [item['text']],
                'begin_time': item['begin_time'],
                'end_time': item['end_time']
            }
            converted_data.append(new_item)
        for entry in converted_data:
            collection_type = request.get_json().get("collection_type")
            if collection_type == "random":
                collection_types = ['Video_library', "Picture_library"]
                collection_type = random.choice(collection_types)
                chunk_clip_mode = query_collection(collection_type=collection_type, questions=entry["text"],
                                                   endpoint=endpoint)

                for item in chunk_clip_mode:
                    item['end_time'] = entry['end_time']
                    item['begin_time'] = entry['begin_time']
                vector_resource.extend(chunk_clip_mode)

            else:
                chunk_clip_mode = query_collection(collection_type=collection_type, questions=entry["text"],
                                                   endpoint=endpoint)
                for item in chunk_clip_mode:
                    item['end_time'] = entry['end_time']
                    item['begin_time'] = entry['begin_time']
                vector_resource.extend(chunk_clip_mode)

        if audio == "on" and len(audio_urls) > 0:
            for item in converted_data:
                item['audio_url'] = random.choice(audio_urls)

                music.append(item)
            # return jsonify(music)
                target_template = {
                    "TimelineIn": "",
                    "TimelineOut": "",
                    "MediaURL": ""
                }
                target_data = []
                for item in music:
                    new_entry = target_template.copy()
                    new_entry["TimelineIn"] = item["begin_time"] / 1000
                    new_entry["TimelineOut"] = item["end_time"] / 1000
                    new_entry["MediaURL"] = item["audio_url"]
                    target_data.append(new_entry)
                        # audio_lists={
                        #     "AudioTrackClips": target_data
                        # }
                    # return jsonify(target_data)
                    # begin_audio = {
                    #     "MediaURL": random.choice(audio_urls),
                    #     'TimelineIn': 0
                    # },
                    #
                    # target_data.extend(begin_audio)
                    # # return jsonify(target_data)
                    format_data = [{
                        "AudioTrackClips":
                            target_data
                    }]

                    # return jsonify(format_data)
                    # 开篇音效 加上 每一句话插入字幕
                    # return jsonify(format_data)
                    # return jsonify(begin_audio)
        else:
            format_data = [{
                "AudioTrackClips": [
                    {

                    },
                ]
            }]
            # return  jsonify(target_data)



    # 不添加素材 就不做任何处理 认为只是添加字幕
    else:
        pass
    video_extensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv']  # 可以根据需要增加更多视频格式
    # 视频后缀
    video_data = [item for item in vector_resource if
                  any(item['Material_url'].endswith(ext) for ext in video_extensions)]

    # 非视频后缀
    non_video_data = [item for item in vector_resource if
                      not any(item['Material_url'].endswith(ext) for ext in video_extensions)]

    # 画中画素材
    pip_clips = [
        {
            "MediaURL": item['Material_url'],
            # 调整变速
            # "Speed": item['Video_length']/(item['end_time']/1000 - item['begin_time']/1000),
            # "Speed": 2,
            "X": 0.25,
            "Y": 0.25,
            "Width": 0.5,
            "Height": 0.5,
            # "In": item['Video_length'] / 1000,
            "Out": item['end_time'] / 1000 - item['begin_time'] / 1000,
            "TimelineIn": item['begin_time'] / 1000,
            "TimelineOut": item['end_time'] / 1000,

        }

        for item in video_data
    ]

    # 去查询 找每一句元素后边的
    image_clips = [
        {
            "MediaURL": item['Material_url'],
            "TimelineIn": item['begin_time'] / 1000,
            "Duration": (item['end_time'] - item['begin_time']) / 1000,  # 图片持续时间

        }
        for item in non_video_data
    ]

    # 插入音效
    # 添加背景音乐
    if background_music == "on":
        background_music = merge_data(data=Content)
        questions = [background_music["text"]]

        # 获取了 单条背景音乐
        background_music_mar = query_collection(collection_type="Audio_library", questions=questions,
                                                endpoint=endpoint)
        # 添加每一个素材 后都添加音乐
        background_music_mar = background_music_mar[0]['Material_url']
        volume = 10

        back_= {
                    "MediaURL": background_music_mar,
                    "Gain": volume

        },
        # return jsonify(back_)
        # format_data[0]['AudioTrackClips'].extend(back_)

        # return jsonify(format_data)

        back_ = [{
            "AudioTrackClips": [
                {
                    "MediaURL": background_music_mar,
                    "Gain": volume

                },
            ]
        }]
        format_data=format_data+back_
        # return jsonify(format_data)


    else:
        pass
        # back_ = [{
        #     "AudioTrackClips": [
        #         {},
        #     ]
        # }]
        # background_music = merge_data(data=Content)
        # questions = [background_music["text"]]
        # # 获取了 单条背景音乐
        # background_music_mar = query_collection(collection_type="Audio_library", questions=questions,
        #                                         endpoint=endpoint)
        # # 添加每一个素材 后都添加音乐
        # background_music_mar = background_music_mar[0]['Material_url']
        # volume = 0
        # back_ = [{
        #     "AudioTrackClips": [
        #         {
        #             "MediaURL": background_music_mar,
        #             "Gain": volume
        #
        #         },
        #     ]
        # }]

    result = create_media_structure(video_clips=MediaUrl, image_clips=image_clips, pip_clips=pip_clips)

    if result["data"] == "":
        return jsonify({"error": result["error"]})
    # 字幕
    ai_template_subtitles = AiTemplateSubtitle.query.filter_by(id=template_id).first()
    # 额外字幕表 跟  ai_style_templates 所有关联信心
    ai_template_titles = AiTemplateTitle.query.filter_by(template_id=template_id).all()
    ai_template_images = AiTemplateImage.query.filter_by(template_id=template_id).all()
    # print(ai_template_titles)
    # 查询有关联的 外键信息
    # foreign_keys = [ai_template_title.style_id for ai_template_title in ai_template_titles]
    # print(foreign_keys)
    # 查询所有外键关联表的信息
    # related_info = BasicTextStyle.query.filter(BasicTextStyle.id.in_(foreign_keys)).all()
    # print(related_info)
    # 先去获取视频时长
    # 获取额外字幕
    # json_data = {'bucket_name': f'{bucket_name}', 'object_key': f'{object_key}'}
    # response =requests.post(url="https://1616a3f397d54f4c9e8569363c5117e2-cn-hangzhou.alicloudapi.com/get_durations", json=json_data)
    # video_time=response.json()["duration"]
    # video_time=float(video_time)
    extra_subtitles = convert_to_subtitle_clip(ai_template_titles, video_time=float(duration))

    # 额外插图
    extra_picture = convert_to_images(ai_template_images, video_time=float(duration))
    # image_clips.extend(extra_subtitles)

    basic_text_style = BasicTextStyle.query.filter_by(id=ai_template_subtitles.style_id).first()

    #
    if ai_template_subtitles.align == 1:
        align = "CenterLeft"
    if ai_template_subtitles.align == 2:
        align = "CenterCenter"
    if ai_template_subtitles.align == 3:
        align = "CenterRight"
    if basic_text_style.bold == 1:
        blod = "true"
    else:
        blod = "false"

    if basic_text_style.italic == 1:
        italic = "true"
    else:
        italic = "false"

    if basic_text_style.underline == 1:
        underline = "true"
    else:
        underline = "false"

    VideoTracks = result["data"]["VideoTracks"] + extra_picture
    AudioTracks = format_data
    # return jsonify(AudioTracks)
    # return jsonify(AudioTracks)
    # return jsonify(back_aduio)
    # return jsonify(AudioTracks)
    VideoTracks = json.dumps(VideoTracks)
    AudioTracks = json.dumps(AudioTracks)

    # 最后生成字幕
    timeline = res.make_subtitles(content=Content, font=basic_text_style.font, blod=blod, italic=italic,
                                  underline=underline,
                                  font_color=basic_text_style.font_color,
                                  shadow_color=basic_text_style.shadow_color,
                                  shadow_size=int(basic_text_style.shadow_size),
                                  outline_colour=basic_text_style.outline_colour, outline=int(basic_text_style.outline),
                                  font_size=int(ai_template_subtitles.size), border_style=basic_text_style.border_style,
                                  align=align, x=float(ai_template_subtitles.x),
                                  y=float(ai_template_subtitles.y),
                                  extra_subtitles=extra_subtitles, VideoTracks=VideoTracks, AudioTracks=AudioTracks)

    if timeline:
        media_url = {"MediaURL": oss_save_url}
        resp = res.main(timeline=timeline, video_url=media_url)
        resp_body = resp.body
        response_dict = vars(resp_body)
        return jsonify({"oss_url": media_url, 'msg': 'success', "response": response_dict})
    else:
        return jsonify({"oss_url": "", "msg": "fail"})


# 查询视频任务状态
@app.route('/select_master/', methods=['POST'])
def select_master():
    res = SelectMasterClient()
    JobId = request.get_json().get("JobId")
    resp = res.main(JobId)
    job_id = resp.body.media_producing_job.job_id
    status = resp.body.media_producing_job.status
    media_id = resp.body.media_producing_job.media_id
    code = resp.body.media_producing_job.code
    return jsonify(job_id=job_id, status=status, media_id=media_id)


# 存入模板
@app.route('/save_template/', methods=['POST'])
def save_template():
    data = request.json
    name = data.get('name')
    if name is None or name.strip() == '':
        return jsonify({"Error": "name字段是必须要传"}), 400
    sub_obj = AiTemplateSubtitle.query.filter_by(name=name).first()
    if sub_obj:
        return jsonify({"Error": "Template already exists"}), 400
    Font = request.get_json().get("Font", "Microsoft YaHei")
    Font_Size = request.get_json().get("Font_Size", 10)
    Font_Color = request.get_json().get("Font_Color", "#ffffff")
    X = request.get_json().get("X", 0)
    Y = request.get_json().get("Y", 0)
    Angle = request.get_json().get("Angle", 0)
    Alignment = request.get_json().get("Alignment", "CenterCenter")
    EffectColorStyle = request.get_json().get("EffectColorStyle", " ")
    Spacing = request.get_json().get("Spacing", 0)
    LineSpacing = request.get_json().get("LineSpacing", 0)
    Italic = request.get_json().get("Italic", 0)
    Underline = request.get_json().get("Underline", 0)
    Bold = request.get_json().get("Bold", 0)

    template = AiTemplateSubtitle(name=name, Font=Font, Font_Size=Font_Size, Font_Color=Font_Color, X=X,
                                  Y=Y, Angle=Angle, Alignment=Alignment, EffectColorStyle=EffectColorStyle,
                                  Spacing=Spacing, LineSpacing=LineSpacing, Italic=Italic, Underline=Underline,
                                  Bold=Bold)
    db.session.add(template)
    db.session.commit()

    # 将上传的数据存到数据库 ORM模型操作
    return jsonify({"msg": "success"})


# 修改 字幕模板接口
@app.route('/edit_template/<int:pk>/', methods=['PUT'])
def edit_template(pk):
    data = request.json
    template = AiTemplateSubtitle.query.filter_by(id=pk).first()
    for key, value in data.items():
        if hasattr(template, key):  # 确保用户对象有该属性
            setattr(template, key, value)
    db.session.commit()
    # 返回更新后的用户数据

    return jsonify({"msg": "修改成功", "data": {
        "name": template.name,
        "Font": template.Font,
        "Font_Size": template.Font_Size,
        "Font_Color": template.Font_Color,
        "X": template.X,
        "Y": template.Y,
        "Angle": template.Angle,
        "Alignment": template.Alignment,
        "EffectColorStyle": template.EffectColorStyle,
        "Spacing": template.Spacing,
        "LineSpacing": template.LineSpacing,
        "Italic": template.Italic,
        "Underline": template.Underline,
        "Bold": template.Bold
    }})


# 删除字幕模板接口
@app.route('/delete_template/<int:pk>/', methods=['DELETE'])
def delete_template(pk):
    template = AiTemplateSubtitle.query.filter_by(id=pk).first()
    db.session.delete(template)
    db.session.commit()
    return jsonify({"msg": "success"})


# 获取单条模板数据 跟所有模板数据接口
@app.route('/template/', methods=['GET'])
@app.route('/template/<int:pk>/', methods=['GET'])
def template(pk=None):
    if pk is not None:
        subtitle_obj = AiTemplateSubtitle.query.filter_by(id=pk).first()
        subtitle_data = {
            "name": subtitle_obj.name,
            "Font": subtitle_obj.Font,
            "Font_Size": subtitle_obj.Font_Size,
            "Font_Color": subtitle_obj.Font_Color,
            "X": subtitle_obj.X,
            "Y": subtitle_obj.Y,
            "Angle": subtitle_obj.Angle,
            "Alignment": subtitle_obj.Alignment,
            "EffectColorStyle": subtitle_obj.EffectColorStyle,
            "Spacing": subtitle_obj.Spacing,
            "LineSpacing": subtitle_obj.LineSpacing,
            "Italic": subtitle_obj.Italic,
            "Underline": subtitle_obj.Underline,
            "Bold": subtitle_obj.Bold
        }
        return jsonify({"msg": "success", "data": subtitle_data})
    else:
        subtitle_obj_list = []
        subtitle_all = AiTemplateSubtitle.query.all()
        for sub in subtitle_all:
            subtitle_data = {
                "name": sub.name,
                "Font_Size": sub.Font_Size,
                "Font_Color": sub.Font_Color,
                "X": sub.X,
                "Y": sub.Y,
                "Angle": sub.Angle,
                "Alignment": sub.Alignment,
                "EffectColorStyle": sub.EffectColorStyle,
                "Spacing": sub.Spacing,
                "LineSpacing": sub.LineSpacing,
                "Italic": sub.Italic,
                "Underline": sub.Underline,
                "Bold": sub.Bold,
                "id": sub.id
            }
            subtitle_obj_list.append(subtitle_data)
        return jsonify({"msg": "获取所有数据", "data": subtitle_obj_list})


# 存资源到向量数据库
@app.route('/save_material/', methods=['POST'])
def save_material():
    """
      {"collection_name" : "Audio_library",
      "data" :{
          "text_content": "Sample text for audio",
          "Material_id": 123,
          "Material_url": "https://example.com/audio",
          "audio_length": "33.3432405s"
      }
      }
      """
    # 批处理大小
    batch_size = 10
    collection_name = request.get_json().get("collection_name")
    data = request.get_json().get("data")
    endpoint = request.get_json().get("endpoint")
    res = process_and_insert_data(collection_name=collection_name, data=data, endpoint=endpoint, batch_size=batch_size)
    return jsonify(res[0])


# 查询向量数据库
@app.route('/filter_material/', methods=['POST'])
def filter_material():
    collection_type = request.get_json().get("collection_type")
    text_content = request.get_json().get("text_content")
    endpoint = request.get_json().get("endpoint")
    res = query_collection(collection_type=collection_type, questions=text_content, endpoint=endpoint)
    return jsonify(res)


# 删除 向量数据库 资源
@app.route('/delete_material/', methods=['POST'])
def delete_material():
    vector_id = request.get_json().get("vector_id")
    collection = request.get_json().get("collection")
    res = delete_vector(collection=collection, vector_id=vector_id)
    return jsonify(res)


def convert_to_images(related_info, video_time):
    """
     处理额外 插图
    """
    print(related_info)
    print("-=============")
    images_clips = []
    for info in related_info:
        if info.type_in == 1:
            if float(info.start_time) > video_time:
                image_clip = {
                    "VideoTrackClips": [{}]
                }
                images_clips.append(image_clip)
                continue  # 使用continue而不是return，继续循环
            else:
                TimelineIn = float(info.start_time)
            # 结束前
        if info.type_in == 2:
            if float(info.end_time) < video_time:
                time = video_time - float(info.end_time)
                Duration = time - float(info.start_time)
                if Duration < 0:
                    image_clip = {
                        "VideoTrackClips": [{}]
                    }
                    images_clips.append(image_clip)
                    continue

            else:
                image_clip = {
                    "VideoTrackClips": [{}]
                }
                images_clips.append(image_clip)
                continue  # 使用continue而不是return，继续循环
            # 开始后
        if info.type_out == 1:
            if float(info.start_time) > video_time:
                image_clip = {
                    "VideoTrackClips": [{}]
                }
                images_clips.append(image_clip)
                continue  # 使用continue而不是return，继续循环
            else:
                TimelineIn = float(info.start_time)
            # 结束前
        if info.type_out == 2:
            if float(info.end_time) < video_time:
                time = video_time - float(info.end_time)
                Duration = time - float(info.start_time)
                if Duration < 0:
                    image_clip = {
                        "VideoTrackClips": [{}]
                    }
                    images_clips.append(image_clip)
                    continue

            else:
                image_clip = {
                    "VideoTrackClips": [{}]
                }
                images_clips.append(image_clip)
                continue  # 使用continue而不是return，继续循环
        image_clip = {
            "VideoTrackClips": [{
                "MediaURL": info.path,
                "TimelineIn": TimelineIn,
                "Duration": Duration,
                "X": info.x,
                'Y': info.y,
                "Type": "Image",
                "Width": info.width,
                "Height": info.height,
            }
            ]}

        images_clips.append(image_clip)
    return images_clips


def convert_to_subtitle_clip(related_info, video_time):
    """
     处理额外字幕的方法
    """

    subtitle_clips = []
    for info in related_info:
        basic_text_style = BasicTextStyle.query.filter_by(id=info.style_id).first()
        if info.type_in == 1:
            if float(info.start_time) > video_time:
                subtitle_clip = {
                    "SubtitleTrackClips": [{}]
                }
                subtitle_clips.append(subtitle_clip)
                continue  # 使用continue而不是return，继续循环
            else:
                TimelineIn = float(info.start_time)
            # 结束前
        if info.type_in == 2:
            if float(info.end_time) < video_time:
                time = video_time - float(info.end_time)
                TimelineOut = time
            else:
                subtitle_clip = {
                    "SubtitleTrackClips": [{}]
                }
                subtitle_clips.append(subtitle_clip)
                continue  # 使用continue而不是return，继续循环
            # 开始后
        if info.type_out == 1:
            if float(info.start_time) > video_time:
                subtitle_clip = {
                    "SubtitleTrackClips": [{}]
                }
                subtitle_clips.append(subtitle_clip)
                continue  # 使用continue而不是return，继续循环
            else:
                TimelineIn = float(info.start_time)
            # 结束前
        if info.type_out == 2:
            if float(info.end_time) < video_time:
                time = video_time - float(info.end_time)
                TimelineOut = time
            else:
                subtitle_clip = {
                    "SubtitleTrackClips": [{}]
                }
                subtitle_clips.append(subtitle_clip)
                continue  # 使用continue而不是return，继续循环
        subtitle_clip = {
            "SubtitleTrackClips": [{
                "TimelineIn": TimelineIn,
                "TimelineOut": TimelineOut,
                "X": info.x,
                'Y': info.y,
                "Type": "Text",
                "Content": info.text,
                "Font": basic_text_style.font,
                "FontSize": info.size,
                "FontColor": basic_text_style.font_color,
                "FontFace": {
                    "Bold": basic_text_style.bold,
                    "Italic": basic_text_style.italic,
                    "Underline": basic_text_style.underline,
                },
                "Alignment": info.align,
                "Shadow": basic_text_style.shadow_size,
                "BackColour": basic_text_style.shadow_color,
                "Outline": basic_text_style.outline,
                "OutlineColour": basic_text_style.outline_colour,
                "BorderStyle": basic_text_style.border_style
            }

            ]}

        subtitle_clips.append(subtitle_clip)

    return subtitle_clips


import functools

from alibabacloud_ice20201109.client import Client as ICE20201109Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ice20201109 import models as ice20201109_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


# class AliTryExceptDecorator:
#     @staticmethod
#     def outer_decorator(func):
#         @functools.wraps(func)
#         def wrapper(*args, **kwargs):
#             try:
#                 result = func(*args, **kwargs)
#             except Exception as e:
#                 result = False, e.message
#             return result
#
#         return wrapper
#
#     def __init_subclass__(cls, **kwargs):
#         super().__init_subclass__(**kwargs)
#         for attr_name, attr_value in cls.__dict__.items():
#             if callable(attr_value) and attr_name not in ["__init_subclass__", "outer_decorator"]:
#                 setattr(cls, attr_name, cls.outer_decorator(attr_value))


class Subtitles():
    @staticmethod
    def create_client() -> ICE20201109Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        # 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        # 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378659.html。
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id="LTAI5t8jMyznaH5dahBisnap",
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret="vQDJGP9D1QIXcFaAIOILrc6OOVIcZz"
        )
        # Endpoint 请参考 https://api.aliyun.com/product/ICE
        config.endpoint = f'ice.cn-hangzhou.aliyuncs.com'
        return ICE20201109Client(config)

    @staticmethod
    def main(
            timeline, video_url
    ) -> None:
        client = Subtitles.create_client()
        submit_media_producing_job_request = ice20201109_models.SubmitMediaProducingJobRequest(
            timeline=f"""{timeline}""",
            output_media_config=f'{video_url}',
            # user_data='{"NotifyAddress":"http://118.31.66.218/api/v1/im/agent/edit-video/callback"}'
            # user_data='{"NotifyAddress":"http://118.31.66.218/api/v1/im/agent/edit-video/callback"}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值d
            resp = client.submit_media_producing_job_with_options(submit_media_producing_job_request, runtime)
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
        return resp

    @staticmethod
    def make_subtitles(content, font, font_color, font_size, align, border_style, shadow_color, shadow_size,
                       VideoTracks,
                       outline_colour, outline, AudioTracks, x, y, underline, italic, blod,
                       extra_subtitles):

        # 准备一个空的SubtitleTracks列表
        subtitle_tracks = []
        # 定义要循环添加的SubtitleEffects参数列表
        # 循环生成SubtitleTrackClips
        # print(bold)
        # 对字幕轨道 做处理
        for i in range(len(content)):
            # 假设这里是你想要的具体参数
            begin_time = content[i]["begin_time"] / 1000  # 示例：每个的开始时间不同
            end_time = content[i]["end_time"] / 1000  # 示例：每个的结束时间不同
            text = content[i]["text"]  # 示例：每个的文字内容不同
            # 构建SubtitleEffects的结构
            # if subtitle_effects is None:
            #     subtitle_effects_list = []
            #     # 使用上面定义的参数列表
            # else:
            #     subtitle_effects_list = subtitle_effects
            # 构建SubtitleTrackClips的结构，包括SubtitleEffects
            subtitle_clip = {
                "SubtitleTrackClips": [{
                    "TimelineIn": begin_time,
                    "TimelineOut": end_time,
                    "Type": "Text",
                    "Content": text,
                    "X": x,
                    "Y": y,
                    "Font": font,
                    "FontSize": font_size,
                    "FontColor": font_color,
                    "FontFace": {
                        "Bold": blod,
                        "Italic": italic,
                        "Underline": underline,
                    },
                    # 对齐
                    "Alignment": align,
                    # 阴影大小
                    "Shadow": shadow_size,
                    # 阴影颜色
                    "BackColour": shadow_color,
                    # 描边或 边框
                    "Outline": outline,
                    # 描边或底色
                    "OutlineColour": outline_colour,
                    # 1边框加阴影outline_colour  3底色background_color
                    "BorderStyle": border_style
                    # "SubtitleEffects": subtitle_effects_list
                }
                ]
            }
            # 将每个生成的SubtitleTrackClips添加到subtitle_tracks中
            subtitle_tracks.append(subtitle_clip)
        subtitle_tracks.extend(extra_subtitles)
        # print(subtitle_tracks)

        # 构建插入的插入语字幕
        # for item in parenthesis:
        #     for clip in item["SubtitleTrackClips"]:
        #         subtitle_clip["SubtitleTrackClips"].append(clip)
        # print(subtitle_tracks)
        # 构建完整的timeline结
        timeline = {
            "VideoTracks": VideoTracks,
            # 将生成的多个SubtitleTrackClips添加到SubtitleTracks中
            "SubtitleTracks": subtitle_tracks,

            # 额外添加一个字幕轨 来做 插入文字的配置
            "AudioTracks": AudioTracks,

        }

        return timeline


# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys

from typing import List

from alibabacloud_ice20201109.client import Client as ICE20201109Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ice20201109 import models as ice20201109_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class SelectMasterClient:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> ICE20201109Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        # 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        # 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378659.html。
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id="LTAI5t8jMyznaH5dahBisnap",
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret="vQDJGP9D1QIXcFaAIOILrc6OOVIcZz"
        )
        # Endpoint 请参考 https://api.aliyun.com/product/ICE
        config.endpoint = f'ice.cn-hangzhou.aliyuncs.com'
        return ICE20201109Client(config)

    @staticmethod
    def main(
            job_id
    ) -> None:
        client = SelectMasterClient.create_client()
        get_media_producing_job_request = ice20201109_models.GetMediaProducingJobRequest(
            job_id=job_id
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            resp = client.get_media_producing_job_with_options(get_media_producing_job_request, runtime)
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
        return resp

    @staticmethod
    async def main_async(
            job_id
    ) -> None:
        client = SelectMasterClient.create_client()
        get_media_producing_job_request = ice20201109_models.GetMediaProducingJobRequest(
            job_id=job_id
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            resp = await client.get_media_producing_job_with_options_async(get_media_producing_job_request, runtime)
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
        return resp


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000, debug=True)
